<template>
  <div>
        <!-- 发表评论 -->
        <div class="cmes-Comment"  v-if="replyShow==-1" >
          <!-- 输入框 -->
          <textarea class="cmes-textarea" cols="103" rows="10" v-model="message.content"></textarea>
          <!-- emoji -->
          <div class="cmes-emoji">
            <div class="cmes-emoji-title" @click="changeShow">
              <p v-if="isShow==0">戳我试试φ(≧ω≦*)♪</p>
              <P v-if="isShow==1">嘿嘿嘿o(*^＠^*)o</P>
            </div>
            <div class="cmes-emoji-icon" v-if="isShow==1">
                <span v-for="ejItem in emoji" :key="ejItem.id" :title="ejItem.name"  class="cmes-emoji-child" @click="toIcon(ejItem.icon)">{{ejItem.icon}}</span>
            </div>
          </div>
          <!-- 用户信息和发布留言 -->
          <div class="cmes-user">
            <div class="cmes-user-email">
              <i class="iconfont icon-yonghutouxiang1 cmes-user-icon"></i>
              <el-tooltip content="昵称不要超过5个字哦" placement="top" effect="light">
                 <el-input placeholder="昵称(必须name*)" v-model="user.nickname" clearable class="cmes-user-ipt" maxlength="5"  @change="isEmpty(user.nickname)"></el-input>
              </el-tooltip>
              <el-tooltip content="要输入正确的邮箱哦" placement="top" effect="light">
                <el-input type="email" placeholder="邮箱(必须email*)" v-model="user.account" clearable class="cmes-user-ipt" @change="rule(user.account)"></el-input>
              </el-tooltip>
            </div>
            <el-checkbox v-model="check">滴，学生卡|I'm not a robot</el-checkbox>
            <!-- <p class="cmes-user-btn" @click="insertMes">BiuBiuBiu~</p> -->
            <el-button size="700px" class="cmes-user-btn"  @click="insertMes" :disabled="!check">BiuBiuBiu~</el-button>
          </div>
        </div>
        <div>
          <div class="cmes-top">
            <!-- 评论条数 -->
            <div class="cmes-title">
              <p>Comments</p>
              <i class="iconfont icon-xian-xuxian"></i>
              <span>{{detailMes.length}}条评论</span>
            </div>
            <div>
              <span v-if="iszhankai" @click="shouqi"><i class="iconfont icon-Group-"></i> 收起回复</span>
              <span  v-else @click="zhankai"><i class="iconfont icon-Group-1">展开回复</i></span>
            </div>
          </div>
            <!-- 评论 -->
            <div>
              <!-- 父级评论 -->
              <div
                v-for="(dsItem,dsIndex) in detailMes"
                :key="dsIndex"
                class="cmesc-child"
                @mouseenter="hoverIndex = dsIndex"
                @mouseleave="hoverIndex = -1">
                <el-divider></el-divider>
                <!-- 评论用户信息 -->
                <div class="cmesc-user">
                  <!-- 头像 -->
                  <!-- <img :src="'data:image/jpeg;base64,'+dsItem.avatar" alt="" class="cmesc-avatar"> -->
                  <img :src="dsItem.avatar" alt="" class="cmesc-avatar">
                  <div>
                    <!-- 昵称等 -->
                    <div class="cmesc-name">
                      <span v-if="dsItem.userType" class="cmesc-blogger">博主</span>
                      <h3 class="cmesc-nickname">{{dsItem.nickname}}</h3>
                      <span class="cmesc-rank">LV{{rank}}</span>
                    </div>
                    <!-- 评论时间 -->
                    <span class="cmesc-time" onload="time()">{{dsItem.time}}</span>
                  </div>
                   <!-- 回复按钮 -->
                    <span
                      class="cmesc-huifu"
                      :class="{'link-item-hover':dsIndex==hoverIndex}"
                      @click="reply(dsItem.mes_id,dsIndex)">回复</span>
                </div>
                <p class="cmesc-content">{{dsItem.content}}</p>
                <div class="cmesc-praise">
                  <span>{{dsItem.praiseCount}}</span>
                  <el-button type="text" class="iconfont icon-aixin_shixin" :class="dsItem.isPraise==null?'praise-gray':'praise-red'" @click="getPraise(dsItem)"></el-button>
                  <span>#{{dsIndex+1}}</span>
                </div>
                <!-- 菜单 -->
                <el-dropdown v-if="isLogin && user_id==dsItem.from_uid" trigger="click"  @command="delReview(1,dsItem.from_uid,dsItem.mes_id)" class="cmesc-caidan">
                  <i class="iconfont icon-caidan cmesc-icon-caidan"></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <!-- 父级回复 -->
                <span v-if="replyShow==dsItem.mes_id" @click="cancelReply" class="cmesc-cancel">取消回复</span>
                <textbox grade = "1" :topicType = "message.topic_type" :typeId = "message.topic_id" :toUid = 'dsItem.mes_id' v-if="replyShow==dsItem.mes_id"></textbox>
                <!-- 子级回复部分 -->
                <div class="cmesc-reply">
                <!-- <el-divider v-if="reItem.to_uids == mesItem.mes_id"></el-divider> -->
                <div
                  v-for="(reItem,reIndex) in dsItem.children.slice(0,len)"
                  :key="reIndex"
                  @mouseenter="hoverReIndex = reIndex"
                  @mouseleave="hoverReIndex = -1">
                  <el-divider></el-divider>
                  <div>
                      <!-- v-if="reItem.to_uids == mesItem.mes_id" -->
                    <!-- <span>{{reItem.content}}</span> -->
                     <!-- @mouseenter="isShowReply=true" @mouseleave="isShowReply=false" -->
                    <div class="cmesc-user">
                      <!-- 子级头像 -->
                      <!-- <img :src="'data:image/jpeg;base64,'+reItem.avatar" alt="" class="cmesc-reply-avatar"> -->
                      <img :src="reItem.avatar" alt="" class="cmesc-reply-avatar">
                      <!-- 子级用户信息 -->
                      <div>
                        <div class="cmesc-name">
                          <span v-if="reItem.userType=='管理员'" class="cmesc-blogger">博主</span>
                          <h3 class="cmesc-nickname">{{reItem.nickname}}</h3>
                          <span class="cmesc-rank">LV{{reItem.rank}}</span>
                        </div>
                        <span class="cmesc-time" onload="time()">{{reItem.time}}</span>
                      </div>
                      <!-- 子级回复按钮 -->
                      <div class="cmesc-caidan">
                        <!-- <i class="iconfont icon-caidan cmesc-icon-zicaidan"></i> -->
                        <span
                        class="cmesc-zihuifu"
                        :class="{'link-item-hover':reIndex==hoverReIndex}"
                        @click="reply(reItem.reId,dsIndex)">回复</span>
                      </div>

                    </div>
                    <!-- 子级评论内容 -->
                    <p class="cmesc-content" @dblclick="delReview(2,reItem.from_userId,reItem.reId)">
                      <span class="cmesc-ante" v-if="reItem.from_childId==null">@{{dsItem.nickname}}</span>
                      <span class="cmesc-ziaite" v-else >@{{reItem.f_cNickName}}</span>
                      {{reItem.repContent}}</p>
                    <el-dropdown v-if="isLogin && user_id==reItem.from_userId" trigger="click"  @command="delReview(2,reItem.from_userId,reItem.reId)" class="cmesc-caidan">
                      <i class="iconfont icon-caidan cmesc-icon-zicaidan"></i>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item>
                          删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                    <!-- <div class="cmesc-praise" @click="getPraise(reItem)">
                      <span>{{reItem.praiseCount}}</span>
                      <i class="iconfont icon-aixin_shixin praise-gray" v-show="reItem.praiseType==0"></i>
                      <i class="iconfont icon-aixin_shixin praise-red" v-show="reItem.praiseType==1"></i>
                    </div> -->

                    <span v-if="replyShow==reItem.reId" @click="cancelReply" class="cmesc-cancel">取消回复</span>
                    <textbox grade = "2"  :fromChildId='reItem.reId' :fromChildName = 'reItem.nickname' :toUid = 'dsItem.mes_id' v-if="replyShow==reItem.reId"></textbox>
                  </div>
                </div>
                <!-- 点击获取更多数据 -->
                  <el-divider></el-divider>
                  <div class="fd-previous">
                    <el-button type="text" v-if="len<dsItem.children.length" @click="more">Previous</el-button>
                    <span v-else-if="dsItem.children.length==0"><i class="iconfont icon-meiyoushuju"></i>还没有回复，快来留言回复吧</span>
                    <span v-else>哎呀，到底了</span>
                  </div>
              </div>
              </div>
            </div>
          </div>
  </div>
</template>
<script>
import textbox from "./textbox.vue"
export default {
  props:['topicType','typeId'],
  inject:['reload'],//注入App里的reload方法
  components:{
    textbox
  },
  data(){
    return {
      emoji:[],
      isShow:0,
      user:{
        user_id:"",
        nickname:"",
        account:"",
        avatar:"",
      },
      message:{
        mes_id:"",
        topic_id:"",
        topic_type:"",
        content:"",
        zd_id:"",
        zd_duration:"",
        time:"",
        from_uid:"",
        to_uids:""
      },
      check:0,
      detailMes:[],
      len:3,
      rank:1,
      replyShow:-1,
      hoverIndex: -1, // 菜单hover索引
      hoverReIndex: -1, // 菜单hover索引
      activeLinkId: 0, // 当前激活的菜单id
      isLogin:"",
      user_id:"",
      praiseCount:0,
      iszhankai:true,
    }
  },
  mounted(){
      this.message.time = new Date();
      this.getEmoji();
      this.getUser();
      this.message.topic_type = this.topicType;
      this.message.topic_id = this.typeId;
      this.isLogin = this.$store.getters.getShow;
      if(this.isLogin){
        this.user_id = this.$store.getters.getUser.user_id;
        // console.log(this.user_id);
      }
      this.getComments(this.user_id);
  },
  methods:{
    // 获取评论信息
    async getComments(user_id){
      let topicType = this.topicType;
      let id = this.typeId;
      const {data:res} = await this.$http.post("getCommentary",{user_id,topicType,id});
      console.log(res);
      if(res.status != 200){
        this.$message.error('查询数据失败');
      }else{
        // this.detailMes = res.message;
        if(res.message.length>0){
          // console.log(this.detailMes);
          // console.log(this.detailMes[0].time);
          // this.time(this.detailMes);
          // this.fileType.time(this.detailMes);
          let arr = res.message;
          this.fileType.time(arr);
          // this.message = res.message;
          for(let i in arr){
            let to_uids = arr[i].mes_id;
            const {data:replyRes} = await this.$http.post("getReplyCommentary",{to_uids});
            //  let replyArr = replyRes.message
            //  for(let n in replyArr){
            //    const {data:replyRes} = await this.$http.post("getReplyCommentary",{to_uids});
            //  }
            arr[i].children = replyRes.message;
            this.fileType.time(replyRes.message);
          }
          // console.log(arr);
          this.detailMes = arr;
          console.log(this.detailMes);
          // this.reload();
        }else{
          console.log("还没有评论");
        }

      }
    },
    more(){
      this.len += 3;
    },
    shouqi(){
      this.len = 0;
      this.iszhankai = !this.iszhankai;
    },
    zhankai(){
      this.len = 3;
      this.iszhankai = !this.iszhankai;
    },
    // 点赞
    async getPraise(item){
      var isLogin = this.$store.getters.getShow;
      // console.log(isLogin);
      // console.log(this.message);
      if(isLogin==false){
        this.$message('叮叮，要先登录才能点赞哦');
        this.$router.push('/login');
      }else{
        // this.praiseCount++;
        // console.log(item);
        // let mes_id = item.mes_id;
        // let praiseType = item.praiseType;
        // let praiseCount = item.praiseCount;
        this.praisemeMes(item);
        let mesObj = {};
        mesObj.mes_id = item.mes_id;
        mesObj.praiseType = item.isPraise;
        mesObj.praiseCount = item.praiseCount;
        // console.log(mesObj);
        mesObj = JSON.stringify(mesObj);
        // if(this.praiseCount>=1 && this.praiseCount<5){
          // 第一步：更改数据表里面praise的true或者false
          const {data:updateRes} = await this.$http.post("updateMesPraise",{mesObj});
          if(updateRes.status != 200){
            this.$message.error('点赞失败');
          }else{
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            // this.praisemeMes(item);
          }

        // }else if(this.praiseCount==5){
        //   this.$message({
        //     message: '警报警报，不要一直点wo',
        //     type: 'warning'
        //   });
        // }else {
        //   this.$message({
        //     message: '不要一直点哦，快去看看其他内容吧',
        //     type: 'warning'
        //   });
        // }
        this.getComments(this.user_id);
      }

    },
     // 添加点赞信息到praiseme表
    async praisemeMes(item){
      console.log(item);
      // 首先查询表中是否有该条数据，无则加，有则删
      let mes_id = item.mes_id;
      let user_id = this.user_id;
      const {data:getMesres} = await this.$http.post("selPraisemeMessage",{mes_id,user_id});
      console.log(getMesres);
      if(getMesres.status != 200){
        this.$message.error('查询数据失败');
      }else{
        let PMArr = getMesres.message;
        let newPrase = {};
        newPrase.Mmes_id = item.mes_id;
        newPrase.praise_userId = this.user_id;
        newPrase.praiseme_time = this.fileType.changeDate(new Date());
        newPrase = JSON.stringify(newPrase);
        console.log(newPrase);
        if(PMArr.length==0){
          console.log("没有该数据");
          if(item.isPraise==null){
            console.log("添加");
            this.addPraise(newPrase);
          }else{
            console.log("删除");
            this.delPraise(item.mes_id,this.user_id)
          }
        }else{
          console.log("有该数据");
          if(item.isPraise==null){
            console.log("修改");
            this.editPraise(newPrase);
          }else{
            console.log("删除");
            this.delPraise(item.mes_id,this.user_id)
          }
        }
      }
    },
    // 添加
    async addPraise(newPrase){
      const {data:res} = await this.$http.post("insertPraiseme",{newPrase});
      console.log(res);
    },
    // 修改
    async editPraise(newPrase){
      const {data:res} = await this.$http.post("updatePraiseme",{newPrase});
      console.log(res);
    },
    // 删除
    async delPraise(mes_id,user_id){
      console.log(mes_id,user_id);
      const {data:res} = await this.$http.post("delPraiseme",{mes_id,user_id});
      console.log(res);
    },
    // 获取是否登录信息
    getUser(){
      let istrue = this.$store.getters.getShow;
      if(istrue){
        this.user = this.$store.getters.getUser;
        this.message.from_uid = this.$store.getters.getUser.user_id;
      }
    },
    // 获取emoji图标数据
    async getEmoji(){
      const {data:res} = await this.$http.get("emoji");
      // console.log(res);
      if(res.status != 200){
        this.$message.error('获取数据失败');
      }else{
        this.emoji = res.message;
      }
    },
    changeShow(){
      this.isShow = !this.isShow;
    },
    // 判断邮箱
    rule(account){
      var verify = /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
        if (!verify.test(account)) {
            this.$message.error('邮箱格式错误, 请重新输入');
            this.user.account = "";
        } else {
            console.log(account);

        }
    },
    // 判断昵称
    isEmpty(nickName){
      if(nickName==""){
        this.$message({
          message: '昵称不能为空哦',
          type: 'warning'
        });
      }
    },
    toIcon(icon){
      this.message.content+=icon;
    },
    // 发表评论：真难呀
    async insertMes(){
      const user = this.user;
      if(user.nickname==""){
        this.$message({
          message: '昵称不能为空哦！可以先登录或者填写昵称哦',
          type: 'warning'
        });
      }
      if(user.account==""){
        this.$message({
          message: '邮箱不能为空哦！可以先登录或者填写邮箱哦',
          type: 'warning'
        });
      }

      if(this.message.content==""){
         this.$message('要先写一些文字才能发表哦');
      }else{
        let istrue = this.$store.getters.getShow;
        this.message.time = new Date();
        // console.log(this.message.time);
        // 这是开始是发表评论
        if(istrue){
          // console.log("这里是登录了");
          // const user_id = this.$store.getters.getUser.user_id;

          // this.message.time = this.changeDate(this.message.time)
          this.message.time = this.fileType.changeDate(this.message.time);
          const mes = JSON.stringify(this.message)
          console.log(mes);
          const {data:res} = await this.$http.post("insertMessage",{mes})
          // console.log(res);
          // console.log("-------------");
          if(res.status!=200){
            this.$message.error('发表评论失败');
          }else{
            this.$message({
              message: '发表成功',
              type: 'success'
            });
            // this.reload();
            this.getComments();
          }
        }else{
          console.log("没登录");
          // 没有登录的话要先创建用户，然后再添加评论数据
          // console.log(this.message);
          // console.log(this.user);
          // console.log("账号");
          // 这里在填写账号的时候要先查询看该账号是否被注册过，如果有：则直接返回id不用再注册，如果没有则注册
          const variate = this.user.account;
          // console.log(variate);
          const {data:selUser} = await this.$http.post("selectUser",{variate});
          if(selUser.status != 200){
              this.$message.error('查询数据失败');
          }else{
            // 查询成功：这里判断返回的数组是否为空，为空则表示未注册，反之注册了，就只需要传个参数id就可以了
            // console.log("这里是查询账号是否存在");
            // console.log(selUser);
            const newUser = JSON.stringify(this.user);
            var arr = selUser.message
            if(arr.length==0){
                //未注册过
                // 先注册user对象
                const {data:resUser} = await this.$http.post("registerUser",{newUser});
                // console.log("未注册过的");
                // console.log(resUser);
                // console.log("========");
                if(resUser.status!=200){
                  this.$message.error('注册失败');
                }else{
                  const {data:selResult} = await this.$http.post("selectUser",{variate});
                  console.log(selResult);
                  this.message.from_uid = selResult.message[0].user_id;
                }
            }else{
              this.message.from_uid = selUser.message[0].user_id;
            }
            // 这里是第一步，看所需数据是否都齐全了
            // console.log("这里是第一步，看所需数据是否都齐全了");
            // console.log(this.message);
            // console.log(this.user);
            const mes = JSON.stringify(this.message)
            const {data:res} = await this.$http.post("insertMessage",{mes})
            if(res.status!=200){
              this.$message.error('发表评论失败');
            }else{
              this.$message({
                message: '发表成功',
                type: 'success'
              });
              // this.reload();
              this.getComments();
            }
          }
        }
      this.message.content  = "";
      this.check=0;
      }
    },
    // 取消回复
    cancelReply(){
      this.replyShow = -1;
    },
    // 回复
    reply(id,index){
      console.log("回复");
      let isShow = this.$store.getters.getShow;
      // console.log(isShow);
      if(isShow){
        this.replyShow = id;
      }else{
        this.$message('要登录才可以回复哦');
      }
      console.log(id);
      console.log(index);
    },
    // 删除评论
    delReview(type,from_userId,mesId){
      // alert("双击删除");
      // console.log(from_userId);
      if(this.isLogin){
        const user_id = this.$store.getters.getUser.user_id;
        // console.log("当前登录的id");
        // console.log(user_id);
        if(user_id==from_userId){
          // alert("删除了");
          this.open(type,mesId);
        }else{
          console.log("不是你写的不能删除");
        }
      }else{
        console.log("你还没有登录哦");
      }
    },
    open(type,mesId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.toDelReview(type,mesId);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除评论
    async toDelReview(type,mesId){
      console.log("删除评论");
      console.log(type);
      console.log(mesId);

      const {data:res} = await this.$http.post("deleteReview",{type,mesId});
      if(res.status != 200){
        this.$message.error('获取评论数据失败');
      }else{
        console.log(res);
        this.getComments();
      }
    },
  }
}
</script>
<style scoped>
/* @import url('../messageBoard/mess.css'); */
@import url('./message.css');
@import url('../messageBoard/mess.css');
</style>
